package com.bstek.demo.urule.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import javax.sql.DataSource;

/**
 * @desc: 主数据源
 * @author: li_y29
 * @create: 2019-12-2
 */
@Configuration
@MapperScan(basePackages = {"com.bstek.demo.urule.mapper"}, sqlSessionFactoryRef = "frameworkDataSourceFactory")
public class FrameworkDataSourceConfig {


    /**
     * 源
     */
    @Bean(name = "frameworkDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.framework")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 工厂
     */
    @Bean("frameworkDataSourceFactory")
    @DependsOn("frameworkDataSource")
    public SqlSessionFactory dataSourceFactory() throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        // 设置拦截器
        factoryBean.setPlugins(new Interceptor[]{mybatisPlusInterceptor()});
        return factoryBean.getObject();
    }

    /**
     * mybatis plus 插件支持
     *
     * @return PaginationInterceptor
     */
    @Bean("mybatisPlusInterceptor2")
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }


    /**
     * 模板
     */
    @Bean("frameworkSqlSessionTemplate")
    @DependsOn("frameworkDataSourceFactory")
    public SqlSessionTemplate sqlSessionTemplate(
            @Qualifier("frameworkDataSourceFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
}
